package cn.alusiaor.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;


/**
 * @author zhuzhiping
 * @date 2019/12/9
 * @description 返回错误信息字符串
 */

@Slf4j
public class ExceptionUtil {
    /**
     * 换行符
     */
    private static final String LINE_SEPARATOR = System.lineSeparator();

    public static void printExceptionMessage(String exceptionType, String exceptionMsg, Throwable throwable, HttpServletRequest request) {
        // 开始记录
        log.error("==========================================printExceptionMessage Start ==========================================");
        // 打印请求 url
        log.error("URL            : {}", request.getRequestURL().toString());
        // 打印 Http method
        log.error("HTTP Method    : {}", request.getMethod());
        // 打印描述信息
        log.error("异常分类        : [{}]", exceptionType);
        // 打印调用 cn.alusiaor.dic.controller 的全路径以及执行方法
        log.error("异常描述        : [{}]", exceptionMsg);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            throwable.printStackTrace(pw);
            String exceptionStackTrace = sw.getBuffer().toString().replaceAll("\\r\\n\\t", LINE_SEPARATOR);
            log.error("异常栈          : [{}]", exceptionStackTrace);
            // 结束记录
            log.error("===========================================printExceptionMessage End ===========================================" + LINE_SEPARATOR);
        } finally {
            pw.close();
        }
    }
}
